﻿using AutoMapper;
using B.S.ProcessEgine.API.Applocations.Commands.FormInfoCommand;
using B.S.ProcessEgine.ErrorCode;
using B.S.ProcessEgine.Infractructure.Interfaces;
using MediatR;

namespace B.S.ProcessEgine.API.Applocations.CommandHandlers.FormInfohandler
{
    public class AddFormInfoCommandHandler:IRequestHandler<AddFormInfoCommand,ApiResult>
    {
        private readonly IFormInfoRepository _formRepository;
        private readonly ILogger<AddFormInfoCommandHandler> _logger;
        private readonly IMapper _mapper;

        public AddFormInfoCommandHandler(IFormInfoRepository formRepository, ILogger<AddFormInfoCommandHandler> logger, IMapper mapper)
        {
            _formRepository = formRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult> Handle(AddFormInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var form = await _formRepository.GetAsync(x => x.FormName == request.info.FormName && x.IsDel == false);
                if (form != null)
                {
                    return ApiResult.Fail("表单名称已存在", StateCodeEnum.Ok);
                }



                var formInfo = _mapper.Map<Domain.Entities.FormInfo>(request.info);

                //添加表单
                var result = await _formRepository.AddAsync(formInfo);

                return result > 0 ? ApiResult.Success(StateCodeEnum.Ok) : ApiResult.Fail("添加表单失败", StateCodeEnum.Fail);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "FormAddCommandHandler Error");
                return ApiResult.Fail("添加表单异常", StateCodeEnum.Exception);
            }
        }
    }
}
